#include "NavigationMapPanel.h"
#include "../../models/ProjectData.h"
#include "../../controller/SignalsBus.h"
#include <QGraphicsScene>
#include <QGraphicsView>
#include "Navigate/RegionGrid.h"


NavigationMapPanel::NavigationMapPanel(){
    scene = nullptr;
    connect(SignalsBus::getInstance(),&SignalsBus::onLoadProject,this,&NavigationMapPanel::refreshUi);
    connect(SignalsBus::getInstance(),&SignalsBus::multipleCheckEnd,this,&NavigationMapPanel::onDisplayResult);
}

void NavigationMapPanel::initComponent()
{
    scene = new QGraphicsScene();
    setRenderHint(QPainter::Antialiasing);
    setFixedSize(this->width(),this->height());

    int rowCount = ProjectData::getInstance()->fixtureRowCount;
    int colCount = ProjectData::getInstance()->fixtureColCount;

    int roiCount = 0;
    int totalFovCount = 0;
    for(int row = 0;row<rowCount;row++)
    {
        for(int col = 0;col<colCount;col++)
        {
            auto roiGrid = new RegionGrid(row,col,QSize(100,100),20);
            scene->addItem(roiGrid);
            connect(roiGrid,&RegionGrid::roiClicked,this,&NavigationMapPanel::onRoiClicked);

            roiHash.insert(roiCount,roiGrid);
            roiCount++;

        }
    }

    setScene(scene);

    for(int i=0;i<roiHash.count();i++)
    {
        totalFovCount += roiHash[i]->getFovCount();
        qDebug()<<"Total fov count = " <<totalFovCount;
    }

    ProjectData::getInstance()->roiButtonCount = roiCount;
    ProjectData::getInstance()->fovButtonCount = totalFovCount;

    qDebug()<<"Fov count "<<ProjectData::getInstance()->fovButtonCount;
    qDebug()<<"ROI Count "<<ProjectData::getInstance()->roiButtonCount;
}

void NavigationMapPanel::onRoiClicked(int roiRow, int roiCol, int fovRow, int fovCol)
{
    QString msg;
    msg = QString("roi (%1,%2),(%3,%4) be clicked").arg(roiRow).arg(roiCol).arg(fovRow).arg(fovCol);
    qDebug()<<msg;


    int cursor = roiRow*(ProjectData::getInstance()->fixtureColCount*ProjectData::getInstance()->fovRowCount*ProjectData::getInstance()->fovColCount)+
                 roiCol*(ProjectData::getInstance()->fovRowCount*ProjectData::getInstance()->fovColCount)+
                 fovRow*ProjectData::getInstance()->fovColCount+
                 fovCol;
    qDebug()<<"Item cursor "<<cursor;

    emit SignalsBus::getInstance()->resultMapClicked(cursor);

}

void NavigationMapPanel::refreshUi()
{
    if(scene!=nullptr)
    {
        scene->clear();
    }
    initComponent();
}

void NavigationMapPanel::onDisplayResult()
{

    int cursor = 0;
    for(int roi = 0;roi<roiHash.count();roi++)
    {
        for(int fov = 0;fov<roiHash[roi]->getFovCount();fov++)
        {
            auto currentFov = roiHash[roi]->getFovs()[fov];
            currentFov->setResult(ProjectData::getInstance()->algorithmHash[cursor]->result.I());
            cursor++;
        }
    }

}
